#pragma once

#include <gpiod.h>

#include <string>
#include <chrono>
#include <thread>
#include <mutex>

#include <libserial/SerialPort.h>

#include <iostream>
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unistd.h>

#include "yj_return.hpp"

void t_thread();

namespace sl = LibSerial;

class uart_v2
{

private:
    std::string _port_name;
    sl::SerialPort _port;
    int _baud_rate;
    int _data_bits;
    int _stop_bits;
    int _byte_timeout_ms;

    float _send_additonal_byte_time;

    std::mutex _uart_mutex;
    yj_return open_flag; // 0:open success 1:open failed



public:
    uart_v2(std::string port_name, int baud_rate, int data_bits, int stop_bits);
    uart_v2(std::string port_name, int baud_rate, int data_bits, int stop_bits, float send_additonal_byte_time);
    ~uart_v2();

    // 禁止拷贝,因为锁不可拷贝
    uart_v2(const uart_v2 &) = delete;            // 禁止拷贝构造函数
    uart_v2 &operator=(const uart_v2 &) = delete; // 禁止拷贝赋值运算符

    yj_return uart_open();
    yj_return uart_close();
    //release_lock:函数返回后是否释放锁
    int uart_send(const uint8_t *data, int len);
    int uart_recv(uint8_t *data, int len);
    int uart_recv_one_by_one(uint8_t *data, int max_len, int frame_timeout_ms);

    uart_v2 &uart_change_baud_rate(int baud_rate);
    uart_v2 &uart_change_send_additonal_btye_time(float send_additonal_byte_time); // 单位为对应波特率下的字节数

    void uart_flush_all();
    std::string uart_get_port_name();
    void uart_print_config();

    std::mutex& uart_get_mutex();
};
